package weaver.batchchanges.util;

import lombok.Getter;
import lombok.Setter;

import java.util.Map;


/**
 * 同源请求服务的接口工具类(单例模式)
 * （未完善）
 */
public class SameOriginRequestsUtil {
    @Setter
    @Getter
    private static String DEFAULT_SCHEME;
    @Setter
    @Getter
    private static String DEFAULT_HOST;

    // 声明一个私有的静态变量来保存单例实例
    private static volatile SameOriginRequestsUtil instance;

    private OkHttpUtils client;

    // 私有构造函数
    private SameOriginRequestsUtil() throws Exception {
        if (DEFAULT_SCHEME == null || DEFAULT_HOST == null) {
            throw new Exception("scheme or host is null");
        }
        // 防止通过反射创建新实例
        if (instance != null) {
            throw new IllegalStateException("Instance already created");
        }
        client = OkHttpUtils.builder(DEFAULT_SCHEME, DEFAULT_HOST);

    }

    public static SameOriginRequestsUtil getInstance(String defaultScheme, String defaultHost) {
        DEFAULT_SCHEME = defaultScheme;
        DEFAULT_HOST = defaultHost;
        return getInstance();
    }

    // 公共的静态方法获取单例实例
    public static SameOriginRequestsUtil getInstance() {
        if (instance == null) { // 第一次检查
            synchronized (SameOriginRequestsUtil.class) {
                if (instance == null) { // 第二次检查
                    try {
                        instance = new SameOriginRequestsUtil();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return instance;
    }

    public String getToken(String appId, String loginId) {
        return getToken("/ssologin/getToken", appId, loginId);
    }

    public String getToken(String url, String appId, String loginId) {
        String result = client.url(url)
                .addParam("appid", appId)
                .addParam("loginid", loginId)
                .post(false).sync();
        return result;
    }

    public String post(String url, Map params, OkHttpUtils.MediaTypeEnum mediaTypeEnum) {
        String result = client.url(url)
                .addParams(params)
                .post(mediaTypeEnum).sync();
//        Object o = JSONObject.parseObject(result, t);
        return result;
    }

}
